package com.example.ftptest.web;

import com.example.ftptest.util.FileManager;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FTPController {

    @Autowired
    FileManager fileManager;

    public FTPClient ftpClient;

    public FTPController() {
        try {
            login();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     * @param multipartFile
     * @param type 类型 0:房源 1:楼盘 2:网店 3:经纪人 在FileManager的String2String定义
     * @param id
     * @throws IOException
     */
    @PostMapping("/{type}/{id}/{children}")
    public String uploadFile(@RequestParam("file") MultipartFile multipartFile, @PathVariable String type,
                           @PathVariable String id, @PathVariable String children) throws IOException{
        try {
            //上传文件后，返回文件相对地址
           StringBuffer sb = new StringBuffer(fileManager.uploadFile(multipartFile, type, id, children, ftpClient));
           sb.append(multipartFile.getOriginalFilename());
           return sb.toString();
        } finally {
//            destroyFtpClient(ftpClient);
        }
    }

    /**
     * 文件 /** **为路径
     * @param res
     * @param request
     * @throws IOException
     */
    @GetMapping("/**")
    public Object downloadFile(HttpServletResponse res,
                             HttpServletRequest request) throws IOException{
//        login();
        try {
            if (request.getRequestURI().contains(".")) {
                fileManager.downloadFile(request.getRequestURI().substring(6), res, ftpClient);
                return null;
            }
            FTPFile[] ftpFiles = fileManager.showFile(request.getRequestURI().substring(6), ftpClient);
            List list = new LinkedList();
            for (FTPFile ftpFile: ftpFiles) {
                list.add(request.getRequestURL().append("/").append(ftpFile.getName()).toString());
            }
            return list;
        } finally {
//            destroyFtpClient(ftpClient);
        }
    }

    /**
     * 删除文件
     * @param request
     * @throws IOException
     */
    @DeleteMapping("/**")
    public boolean deleteFile(HttpServletRequest request) throws IOException{
//        login();
        try {
            return fileManager.deleteFile(request.getRequestURI().substring(6), ftpClient);
        } finally {
//            destroyFtpClient(ftpClient);
        }
    }

    /**
     * 删除目录
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/**")
    public boolean deleteDirectory(HttpServletRequest request) throws IOException{
//        login();
        try {
            return fileManager.deleteDirectory(request.getRequestURI().substring(6), ftpClient);
        } finally {
//            destroyFtpClient(ftpClient);
        }
    }

    /**
     *  建立FTP链接
     * @throws IOException
     */
    private void login() throws IOException{
        ftpClient = new FTPClient();
        try {
            ftpClient.connect("127.0.0.1", 2121);
            ftpClient.login("admin", "123456");
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("GBK");
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
            conf.setServerLanguageCode("zh");
        } catch (IOException e) {
            e.printStackTrace();
            destroyFtpClient(ftpClient);
            throw new RuntimeException("FTP客户端出错！", e);
        }
    }

    /**
     * 摧毁ftp链接
     * @param ftpClient
     */
    private void destroyFtpClient(FTPClient ftpClient) {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
}
